const express = require("express");
const Router = express.Router();

const {
  createTime
} = require("../../utils/time/time");

const configSql = require("../../db/db");
let adress_list = []
// 数据库表名   allType_list

// 所有分类列表(获取子项)
Router.get('/get_all_category', (req, res) => {
  let {
    type
  } = req.query


  let sql = `select * from sub_list where type_id='${type}'`


  configSql(sql).then(result => {

    result = result.map((v, i) => {
      let sql1 = `select name from address_list where id='${v.address}'`
      configSql(sql1).then(d => {
        v["address_name"] = d[0].name
      })
      return v
    })
    setTimeout(() => {
      res.send({
        code: 0,
        msg: "获取成功",
        data: result,
      })
    }, 100)


  })
})

// 新增分类
Router.post("/add_category", (req, res) => {
  let {
    T_name,
    typeid,
    address
  } = req.body;
  let type = ''

  adress_list.forEach((item) => {
    if (item.name == address) {
      type = item.id
    }
  })


  let sql1 = `insert into sub_list(name,type_id,address)values('${T_name}','${typeid}','${type}')`

  configSql(sql1).then(data => {
    let sql = `insert into type_list(type,sub_list_id) values ('${typeid}','${data.insertId}')` // 添加主表的type
    configSql(sql).then((result) => {
      res.send({
        code: 0,
        msg: "新增成功"
      })
    })
  })
});

// 删除分类
Router.post("/delete_category", (req, res) => {
  let {
    T_id,
    type
  } = req.body;
  let sql = `DELETE from sub_list where id='${T_id}'and type_id='${type}'`;
  configSql(sql).then((data) => {
    let sql1 = `DELETE from type_list where sub_list_id='${T_id}' and type='${type}'`
    configSql(sql1).then(d => {
      res.status(200).send({
        code: 0,
        msg: "删除成功",
      });
    })
  });
});

// 修改分类
Router.post("/edit_category", (req, res) => {
  let {
    id,
    type_id,
    name,
    address,
  } = req.body;
  let sql = `update sub_list set name='${name}',address='${address}' where id='${id}' and type_id='${type_id}'`;
  configSql(sql).then((data) => {
    res.send({
      code: 0,
      msg: "修改成功",
    });
  });
});

// 查询分类(获取所有的类型)
Router.post("/select_category", (req, res) => {
  let {
    role
  } = req.body;
  if (role !== 1) {
    res.status(404).send({
      code: 404,
      msg: "查找不到接口",
    });
  }
  let sql = `select * from travel_type_list where type='${type}'`;
  configSql(sql).then((data) => {
    res.status(200).send({
      code: 0,
      msg: "查询成功",
    });
  });
});



// 获取所有的位置
Router.get("/all_adress", (req, res) => {
  let {
    type
  } = req.query
  if (!type) {
    res.send({
      code: 500,
      msg: "参数缺失"
    })
  }
  let sql = `select * from address_list where type='${type}'`
  configSql(sql).then(result => {
    adress_list = result
    res.send({
      code: 0,
      msg: "获取成功",
      result
    })
  })
})







// 导出路由
module.exports = Router;